#include <stdlib.h>
#include "typedef.h"
#include "env.h"
#include "netctrl.h"

#define IP_ADDR_LEN     (256)
#define NET_BUFFER_LEN  (1032)

extern int net_open(char* ip, int port);
extern int net_send(char* data, int size);
extern int net_read(char* buffer, int buflen, int *readsize);
extern void net_close();

int netctrl_connect()
{
    if (net_open(g_server_ip, g_port) != SUCCESS)
    {
    	return ERROR;
    }

    return SUCCESS;
}

int netctrl_send(char* package, int size)
{
	return net_send(package, size);
}

int netctrl_listen(SERVER_LISTEN_CALLBACK_FUNC func)
{
	int  readsize;
    char buffer[NET_BUFFER_LEN];

	if (!func)
		return ERROR;

    while(TRUE)
    {
    	int ret = net_read(buffer, NET_BUFFER_LEN, &readsize);
    	if (ret == FATAL)
    		return FATAL;
    	else if (ret == ERROR)
    		return ERROR;
    	else
    	{
    		if (readsize == 0)
    			continue;

    		func(buffer, readsize);
    	}
    }

    return SUCCESS;
}

void netctrl_close()
{
    net_close();
}
